# 监控按钮
import time
from machine import Pin

import zz_code


def of(pin):
    return ZZ_BTN(pin)


class ZZ_BTN():
    def __init__(self, pin: Pin):
        # 定时器0
        self.pin = pin
        self.pin.irq(self.pin_irq, trigger=Pin.IRQ_RISING)
        self.enable = True
        self.vibrate_ms = 450  # 防按钮抖动（毫秒）
        print(f"防按钮抖动: {self.vibrate_ms}毫秒")
        self.click_data = {
            "time_begin": 0,
            "event": None,
        }
        self.click2_data = {
            "time_begin": 0,
            "wait_ms": 750,  # 750毫秒内点击2次，算成功
            "click_time_begin": 0,
            "click_count": 0,
            "click_total": 2,
            "event": None,
        }

    def service_close(self):
        # print(f"btn服务关闭")
        self.enable = False

    def service_open(self):
        # print(f"btn服务开启")
        self.enable = True

    def service_is(self, enable):
        res = self.enable == enable
        return res

    # 绑定单击事件
    def bind_click(self, event):
        self.click_data['event'] = event
        pass

    # 绑定双击事件
    def bind_click2(self, event, wait_ms=750):
        self.click2_data['event'] = event
        self.click2_data['wait_ms'] = wait_ms
        pass

    def pin_irq(self, pin):
        if self.service_is(False):
            return

        val = pin.value()
        # print(f"pin_irq: {val}")

        now = time.time_ns()
        if self.click_data['event'] is not None:
            # 单击事件处理
            time_begin = self.click_data["time_begin"]
            time_span = zz_code.time_diff_ms(now, time_begin)
            # print(f"click: {now} - {time_begin} = {time_span} > {span_ms}")
            if val == 0:
                if time_span > self.vibrate_ms:  # 按钮抖动
                    self.service_close()
                    # print("单击事件，执行回调")
                    self.click_data["time_begin"] = 999999999999999000
                    event = self.click_data['event']
                    event(self, pin)
            else:
                # 松开，重置开始时间
                self.click_data["time_begin"] = 0

        if self.click2_data['event'] is not None:
            # 多次点击事件处理
            time_begin = self.click2_data["time_begin"]
            time_span = zz_code.time_diff_ms(now, time_begin)
            if val == 0:
                if time_span > self.vibrate_ms:  # 按钮抖动300ms
                    self.click2_data["time_begin"] = 999999999999999000

                    click_count = self.click2_data["click_count"]
                    click_total = self.click2_data["click_total"]
                    click_time_begin = self.click2_data["click_time_begin"]
                    wait_ms = self.click2_data["wait_ms"]  # 等待时长

                    wait_time_span = zz_code.time_diff_ms(now, click_time_begin)
                    # print(f"click: click_count={click_count}, wait_time_span={wait_time_span}")
                    if wait_time_span > wait_ms:
                        # 超时，重置
                        print(f"超时，重置")
                        click_count = 0

                    if click_count == 0:
                        # 第1次点击-开始计时
                        self.click2_data["click_time_begin"] = time.time_ns()
                    click_count += 1
                    self.click2_data["click_count"] = click_count

                    print(f"click: click_count={click_count}")
                    if click_count >= click_total:
                        # print("单击事件，执行回调")
                        self.service_close()
                        self.click2_data["click_count"] = 0
                        event = self.click2_data['event']
                        event(self, pin)

            else:
                # 松开，重置开始时间
                self.click2_data["time_begin"] = 0
